package com.app.utils;


import java.io.*;
import java.net.URL;
public class ImgUtils {
    /**从URL中获取图片输入流
     * 并创建本地文件
     * @param imageUrl
     * @param savePath
     * @return
     * @throws Exception
     */
    public static File getImageFileFromUrl(String imageUrl, String savePath) throws Exception {
        // 从URL中获取图片输入流
        URL url = new URL(imageUrl);
        InputStream in = url.openStream();


        // 构建保存路径
        String[] split = imageUrl.split("/");
        String fileName = split[split.length - 1];
        File file = new File(savePath + fileName);
        if(!file.exists()) {
            file.createNewFile();
        }

        // 写入文件
        FileOutputStream out = new FileOutputStream(file);
        byte[] buffer = new byte[4096];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        out.close();
        in.close();

        return file;
    }

    /**
     * 根据URL地址获取文件
     * 得到file对象
     * @param path URL网络地址
     * @return File
     */
    public static File getFileByHttpURL(String path){
        String newUrl = path.split("[?]")[0];
        String[] suffix = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = suffix[suffix.length - 1];
        File file = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            file = File.createTempFile("report",fileName);//创建临时文件
            URL urlFile = new URL(newUrl);
            inputStream = urlFile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static void main(String[] args) throws Exception {
        //File file = ImgUtils.getImageFileFromUrl("【你的图片网络url】", "【你要保存的本地文件位置】");
        File file = ImgUtils.getFileByHttpURL("【你的图片网络url】");
        System.out.println("file.length() = " + file.length());
    }
}
